import { ref } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';

export function useCrud(config) {
  console.log('useCrud', config)
  const { apis, formFields, tableColumns, searchFields, page: pageConfig } = config;

  // 数据列表
  const tableData = ref([]);
  const tableLoading = ref(false);
  // 搜索
  const searchParams = ref({});
  // 下拉框选项数据
  const selectOptions = ref({});
  // 级联选择数据
  const cascaderOptions = ref({});
  // 分页
  const page = ref({
    pageCurrent: 1,
    pageSize: 10,
    total: 0,
    ...pageConfig, // 外部传入的分页
  });
  // 表单数据
  const formData = ref({});
  const dialogVisible = ref(false);
  // 是否编辑
  const isEdit = ref(false);
  // 表单ref
  const formRef = ref(null);
  // 校验规则
  const formRules = ref({});

  const initFormData = () => {
    formData.value = {};
    formFields.forEach((field) => {
      formData.value[field.prop] = field.defaultValue || '';
    });
  };
  const initSearchParams = () => {
    searchParams.value = {};
    searchFields.forEach((field) => {
      searchParams.value[field.prop] = field.defaultValue || '';
    });
    console.log('初始化搜索条件', searchParams.value)
  };
  const initFormRules = () => {
    formRules.value = {};
    formFields.forEach((field) => {
      if (field.rules) {
        formRules.value[field.prop] = field.rules;
      }
    });
  };

  // 获取数据
  const fetchData = async () => {
    console.log('fetchData')
    tableLoading.value = true;
    const params = {
      ...searchParams.value,
      page: page.value.pageCurrent,
      pageSize: page.value.pageSize
    };
    console.log('获取列表参数', params)
    const res = await apis.getList(params)
    console.log('获取数据', res)

    page.value.total = res.data.total || 0;
    tableLoading.value = false;
    tableData.value = res.data.list || res.data;
  };

  // 获取搜索下拉框选项数据
  const fetchSelectOptions = async () => {
    for (const field of searchFields) {
      if (field.type === 'select' && field.api) {
        const response = await field.api();
        selectOptions.value[field.prop] = response.data.map(item => ({
          label: item.label || item.name,
          value: item.value || item.id,
        }));
      } else {
        selectOptions.value[field.prop] = field.options
      }
    }
  };

  // 获取新增/编辑下拉框数据
  const fetchDialogSelect = async (field) => {
    if (field.type === 'select' && field.api) {
      const response = await field.api();
      selectOptions.value[field.prop] = response.data.map(item => ({
        label: item.label || item.name,
        value: item.value || item.id,   
      }));
    } else {
      selectOptions.value[field.prop] = [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
      ]
    }
  }

  // 获取新增/编辑级联选择数据
  const fetchDialogCascader = async (field) => {
    if (field.type === 'cascader' && field.api) {
      const response = await axios.get(field.api);
      cascaderOptions.value[field.prop] = response.data;
    } else {
      cascaderOptions.value[field.prop] = [
        {
          "label": "省份1",
          "value": "1",
          "children": [
            {
              "label": "城市1",
              "value": "11"
            },
            {
              "label": "城市2",
              "value": "12"
            }
          ]
        },
        {
          "label": "省份2",
          "value": "2",
          "children": [
            {
              "label": "城市3",
              "value": "21"
            }
          ]
        }
      ]
    }
  }

  // 获取搜索级联选择数据
  const fetchCascaderOptions = async () => {
    for (const field of searchFields) {
      if (field.type === 'cascader' && field.api) {
        const response = await axios.get(field.api);
        cascaderOptions.value[field.prop] = response.data;
      } else {
        cascaderOptions.value[field.prop] = [
          {
            "label": "省份1",
            "value": "1",
            "children": [
              {
                "label": "城市1",
                "value": "11"
              },
              {
                "label": "城市2",
                "value": "12"
              }
            ]
          },
          {
            "label": "省份2",
            "value": "2",
            "children": [
              {
                "label": "城市3",
                "value": "21"
              }
            ]
          }
        ]
      }
    }
  };

  // 打开新增/编辑对话框
  const openDialog = async (row = null) => {
    if (row) {
      isEdit.value = true;
      formData.value = { ...row };
    } else {
      isEdit.value = false;
      initFormData();
    }
    if (formRef.value) {
      formRef.value.reset()
    }
    dialogVisible.value = true;
    for (const field of formFields) {
      if (field.type === 'cascader') {
        await fetchDialogCascader(field);
      } else if (field.type ==='select') {
        await fetchDialogSelect(field);
      }
    }
  };

  // 提交
  const submitForm = async () => {
    // 校验
    const isValid = await formRef.value.validate();
    if (isValid === true) {
      console.log('校验通过')
      if (isEdit.value) {
        await apis.update(formData.value)
        MessagePlugin.success('编辑成功');
      } else {
        await apis.save(formData.value)
        MessagePlugin.success('新增成功');
      }
      dialogVisible.value = false;
      queryPage();
    } else {
      console.log('校验失败', isValid)
      return
    }
  };

  // 删除
  const deleteData = async (id, name = '') => {
    const confirmDia = DialogPlugin({
      header: '提示',
      body: name ? `是否删除【${name}】？` : '是否删除该条数据?',
      confirmBtn: '确认',
      cancelBtn: '取消',
      onConfirm: () => {
        apis.delFunc({id}).then(() => {
          queryPage();
        })
        confirmDia.hide();
      },
      onClose: () => {
        confirmDia.hide();
      }
    })
  };

  const handleSearch = () => {
    page.value.pageCurrent = 1
    queryPage();
  };
  const resetSearch = () => {
    console.log('resetSearch')
    initSearchParams();
    handleSearch();
  };
  const handlePageChange = (page) => {
    page.value.pageCurrent = page;
    queryPage();
  };
  // 导出
  const handleExport = async () => {
    const params = {
      ...searchParams.value,
      page: page.value.pageCurrent,
      pageSize: page.value.pageSize
    };
    const res = await apis.exportFunc(params)
    console.log('导出数据', res)
  };

  // 防抖
  const queryPage = useDebounceFn(() => {
    fetchData()
  }, 300)

  // 初始化
  initSearchParams();
  initFormRules();
  fetchSelectOptions();
  fetchCascaderOptions();

  return {
    searchFields,
    formRef,
    tableData,
    tableLoading,
    formData,
    dialogVisible,
    isEdit,
    tableColumns,
    formFields,
    searchParams,
    selectOptions,
    cascaderOptions,
    page,
    formRules,
    fetchData,
    openDialog,
    submitForm,
    deleteData,
    handleSearch,
    resetSearch,
    handlePageChange,
    handleExport,
  };
}